package com.tenement.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.tenement.dao.*;
import com.tenement.domain.TenementHouse;
import com.tenement.domain.TenementImg;
import com.tenement.domain.TenementLog;
import com.tenement.domain.TenementUser;
import com.tenement.service.HouseService;
import com.tenement.utils.Config;
import com.tenement.utils.HoseOrClientVo;
import com.tenement.utils.Tools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static org.apache.tomcat.util.http.fileupload.FileUtils.deleteDirectory;

/**
 * @ClassName : HouseServiceImpl  //类名
 * @Description : 房屋信息服务接口实现类  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-06-06 11:24  //时间
 */
@Service
public class HouseServiceImpl implements HouseService {

    /**
     *房屋信息dao
     */
    @Resource
    TenementHouseMapper tenementHouseMapper;

    /**
     * 日志dao
     */
    @Resource
    TenementLogMapper tenementLogMapper;

    /**
     * 图片
     */
    @Resource
    TenementImgMapper tenementImgMapper;

    @Resource
    private Config config;

    /**
     * 查询所有（分页，条件）
     * @param tenementHouse 房屋信息
     * @param page 当前页数
     * @param limit 显示行数
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public List<TenementHouse> findAll(TenementHouse tenementHouse, Integer page, Integer limit, String startDate, String endDate) {
        PageHelper.startPage(page,limit);
        return tenementHouseMapper.findAll(tenementHouse,startDate,endDate);
    }

    /**
     * 总行数
     * @param house 房屋信息
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Long overCount(TenementHouse house, String startDate, String endDate) {
        return tenementHouseMapper.overCount(house,startDate,endDate);
    }

    /**
     * 新增
     * @param house 房屋信息
     * @param user 用户
     * @param ip ip地址
     * @return
     */
    @Override
    public int add(TenementHouse house, TenementUser user, String ip){

        Integer houseId=tenementHouseMapper.overCountId();
        house.setUserId(clientIdentity(houseId.toString()));
        house.setHouseId(UUID.randomUUID().toString().replaceAll("-",""));
        house.setRevision(1);
        house.setCreatedBy(user.getUserName());
        //house.setCreatedTime(new Date());

        TenementLog log=new TenementLog();
        log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
        log.setLogType(1);
        StringBuffer logBody=new StringBuffer();
        Tools.logHouseMod(house,logBody);
        log.setLogBody(logBody.toString());
        log.setLogTitle("新增房源信息");
        log.setLogIp(ip);
        log.setCreatedBy(user.getUserName());
        tenementLogMapper.insertSelective(log);
        return tenementHouseMapper.insertSelective(house);
    }

    /**
     * 生成id
     * @param clientIdentity
     * @return
     */
    private String clientIdentity(String clientIdentity) {

        int y = 6 - clientIdentity.length();
        String cid = "ID";
        for (int i = 0; i < y; i++) {
            cid += "0";
        }
        cid += clientIdentity;
        return cid;
    }

    /**
     *
     * @param house 租房信息
     * @param user 用户
     * @param ip ip地址
     * @return
     */
    @Override
    public int update(TenementHouse house, TenementUser user, String ip) {
        house.setUpdatedBy(user.getUserName());
        house.setUpdatedTime(new Date());

        TenementLog log=new TenementLog();
        log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
        log.setLogType(4);
        StringBuffer logBody=new StringBuffer();
        Tools.logHouseMod(house,logBody);
        log.setLogBody(logBody.toString());
        log.setLogTitle("修改房源信息");
        log.setLogIp(ip);
        log.setCreatedBy(user.getUserName());
        tenementLogMapper.insertSelective(log);
        return tenementHouseMapper.updateByPrimaryKeySelective(house);
    }

    /**
     * 单个删除
     * @param id 租房信息id
     * @param user
     * @param ip
     * @return
     */
    @Override
    public int delete(String id, TenementUser user, String ip) {
        TenementHouse house=tenementHouseMapper.selectByPrimaryKey(id);
        house.setRevision(0);
        TenementLog log=new TenementLog();
        log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
        log.setLogType(2);
        StringBuffer logBody=new StringBuffer();
        Tools.logHouseMod(house,logBody);
        log.setLogBody(logBody.toString());
        log.setLogTitle("删除房源信息");
        log.setLogIp(ip);
        log.setCreatedBy(user.getUserName());
        tenementLogMapper.insertSelective(log);
        return tenementHouseMapper.updateByPrimaryKeySelective(house);
    }

    /**
     * 批量删除
     * @param ids
     * @param user
     * @param ip
     * @return
     */
    @Override
    public int deleteAll(String[] ids, TenementUser user, String ip) {
        List<String> list=new ArrayList<>(Arrays.asList(ids));

        TenementLog log=new TenementLog();
        log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
        log.setLogType(2);
        List<TenementHouse> houses=tenementHouseMapper.findAllId(list);
        StringBuffer logBody=new StringBuffer();
        Tools.logHouseMods(houses,logBody);
        log.setLogBody(logBody.toString());
        log.setLogTitle("批量删除房源信息");
        log.setLogIp(ip);
        log.setCreatedBy(user.getUserName());
        tenementLogMapper.insertSelective(log);
        int row=tenementHouseMapper.updateAllPrimaryKey(list);

        if(row>0){
            row=list.size();
        }
        return row;
    }

    @Override
    public TenementHouse findById(String houseId) {
        return tenementHouseMapper.selectByPrimaryKey(houseId);
    }

    @Override
    public List<TenementHouse> selectAll() {
        return tenementHouseMapper.selectAll();
    }

    /**
     * 查询所有图片
     * @param houseId
     * @param imgType
     * @return
     */
    @Override
    public List<TenementImg> selectAllImg(String houseId,String imgType) {
        return tenementImgMapper.findAll(houseId,imgType);
    }

    /**
     * 新增图片
     * @param imgUrl
     * @param houseId
     * @return
     */
    @Override
    public int addImg(String imgUrl, String houseId) {
        TenementImg img=new TenementImg();
        img.setImgId(UUID.randomUUID().toString().replaceAll("-",""));
        img.setImgUrl(imgUrl);
        img.setImgType(0);
        img.setHouseId(houseId);
        img.setRevision(1);
        return tenementImgMapper.insert(img);
    }

    /**
     * 删除图片
     * @param imgId
     * @return
     */
    @Override
    public int deleteImg(String imgId) {
        TenementImg img=tenementImgMapper.selectByPrimaryKey(imgId);
        int row=tenementImgMapper.deleteByPrimaryKey(imgId);
        String[] imgUrls=img.getImgUrl().split("/");
        String imgUrl="";
        for (int i=0;i<imgUrls.length;i++){
            if("upload".equals(imgUrls[i])){
                imgUrl+=config.getDir()+"/"; //存储的目标地址
            }else if(i==imgUrls.length-1){
                imgUrl+=imgUrls[i];
            }else{
                imgUrl+=imgUrls[i]+"/";
            }
        }

        if(row>0) {
            File file = new File(imgUrl);
            if (file.isFile()){
                file.delete();
            }else{
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int findHouseArea(String houseArea) {
        return tenementHouseMapper.findHouseArea(houseArea);
    }
}
